<template>
  <!-- 登录页 -->
  <div class="modal" v-show="$store.state.isOpenLogin">
    <div @click="colseLogin" class="modal_bd"></div>
    <div class="modal_content">
      <img
        @click="colseLogin"
        class="colse"
        src="../assets/images/login/userArrow.png"
        alt=""
      />
      <section>
        <span :class="{ active: !showphone }" @click="showphone = !showphone"
          >手机号登录</span
        >
        <span :class="{ active: showphone }" @click="weixinlogin"
          >微信扫码登录</span
        >
      </section>
      <div class="phone_login" v-show="!showphone">
        <div class="line tanxin">
          <input type="text" v-model="phonenum" placeholder="请输入手机号" />
        </div>
        <div class="verify_box">
          <slide-verify
            :l="42"
            :r="10"
            :w="362"
            :h="140"
            slider-text="向右滑动"
            @success="onSuccess"
            @fail="onFail"
            @refresh="onRefresh"
            :style="{ width: '100%' }"
            class="slide-box"
            ref="slideBlock"
          ></slide-verify>
        </div>
        <div class="line tanxin">
          <input type="text" v-model="code" placeholder="请输入短信验证码" />
          <div class="btn" @click="btnyzm">
            <p v-if="show">获取验证码</p>
            <p v-else class="p2">{{ time }}</p>
          </div>
        </div>
        <div class="btn_login" @click="goLogin">登录</div>
      </div>
      <div id="weixin" v-show="showphone"></div>
    </div>
  </div>
</template>

<script>
import { validateTelephone } from "../utils/index";
import { getCodeApi, LoginApi, BindWeixinApi } from "@/request/api";
export default {
  data() {
    return {
      // 手机号登录/微信二维码登录
      showphone: false,
      // 手机号
      phonenum: "15881825417",
      // 显示获取验证码 / 显示倒计时
      show: true,
      // 验证码倒计时
      time: 10,
      //初始化定时器
      timer: "",
      //   短信验证码
      code: "4514",
    };
  },
  methods: {
    // 关闭登录模态框
    colseLogin() {
      this.$store.commit("changeOpenLogin", false);
    },
    // 拼图成功的时候
    onSuccess(times) {
      console.log("验证通过，耗时" + times + "毫秒");
      this.msg = `login success, 耗时${(times / 1000).toFixed(1)}s`;
    },
    // 拼图失败的时候
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新的时候
    onRefresh() {
      this.msg = "再试一次";
    },
    // 点击验证码
    btnyzm() {
      let result = validateTelephone(this.phonenum);
      if (this.phonenum.trim() === "" && result) {
        alert("请输入正确的手机号");
      } else {
        getCodeApi({
          phone: this.phonenum,
        }).then((res) => {
          if (res.data.code === 0) {
            this.show = false;
            this.starTime();
          } else {
            alert("发送验证码失败");
          }
        });
      }
    },
    // 倒计时
    starTime() {
      this.timer = setInterval(() => {
        this.time--;
        if (this.time <= 0) {
          clearInterval(this.timer);
          this.show = true;
          // 再次初始化倒计时数字
          this.time = 10;
        }
      }, 1000);
    },
    // 点击登录
    goLogin() {
      // 判断手机号是否有问题
      if (!validateTelephone(this.phonenum)) {
        this.$store.dispatch("asyncclosetoast", {
          content: "请重新输入手机号",
          icon: "danger",
        });
        return;
      }
      // 判断验证码是否有问题
      if (this.code.trim() === "") {
        this.$store.dispatch("asyncclosetoast", {
          content: "请输入验证码",
          icon: "danger",
        });
        return;
      }
      // 判断滑块是否有问题
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        this.$store.dispatch("closeToast", {
          content: "请滑动拼图",
          icon: "danger",
        });
        return;
      }
      // 都没问题则发起登录请求
      // 获取uuid
      let uuid = sessionStorage.getItem("uuid");
      if (uuid) {
        BindWeixinApi({
          verifyCode: this.code,
          phone: this.phonenum,
          uuid: uuid,
        }).then((res) => {
          if (res.data.code === 0) {
            // 存储token
            localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
            // 提示成功
            this.$store.dispatch("asyncclosetoast", {
              content: "登录成功",
              icon: "success",
            });
            // 关闭登录框
            this.$store.commit("changeOpenLogin", false);
            // 更新header组件
            this.$emit("updateKeyFn");
            // 删除uuid
            sessionStorage.removeItem("uuid");
          }
        });
      } else {
        LoginApi({
          verifyCode: this.code,
          phone: this.phonenum,
        }).then((res) => {
          if (res.data.code === 0) {
            console.log(res);
            // 存储token
            localStorage.setItem("x-auth-token", res.data["x-auth-token"]);
            // 弹出登录成功提示
            this.$store.dispatch("asyncclosetoast", {
              content: "登录成功",
              icon: "success",
            });
            // 关闭登录模态框
            this.$store.commit("changeOpenLogin", false);
            // 更新header组件
            this.$emit("updateKeyFn");
          }
        });
      }
    },
    // 点击切换微信登录
    weixinlogin() {
      this.showphone = true;
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          window.btoa(process.env.VUE_APP_STATE_URL + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogICAgZGlzcGxheTogbm9uZTsNCn0NCg0KLmltcG93ZXJCb3ggLnFyY29kZXsNCiAgICBtYXJnaW4tdG9wOiAyMHB4Ow0KfQ0KY2Qg",
      });
    },
  },
};
</script>
 
<style lang = "less" scoped>
@import "../assets/base.less";
.modal {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  .modal_bd {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .modal_content {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    margin: auto;
    background: url(../assets/images/login/loginBg.png);
    width: 555px;
    height: 423px;
    .colse {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }
    #weixin {
      width: 300px;
      margin: auto;
    }
    section {
      display: flex;
      justify-content: center;
      padding-top: 40px;
      margin-bottom: 30px;
      span {
        color: #ccc;
        cursor: pointer;
        &:nth-of-type(1) {
          border-right: 1px solid #ccc;
          padding-right: 10px;
          margin-right: 10px;
        }
        &.active {
          color: #000;
        }
      }
    }
    .line {
      width: 360px;
      margin: 0 auto 20px;
      height: 50px;
      input {
        flex: 1;
        text-indent: 1em;
        outline: none;
      }
      .btn {
        width: 90;
        height: 50px;
        line-height: 50px;
        color: #fff;
        background: @blue;
        margin-left: 10px;
        cursor: pointer;
        p {
          text-align: center;
          width: 90px;
          height: 50px;
          &.p2 {
            background-color: #ccc;
            font-size: 16px;
          }
        }
      }
    }
    .btn_login {
      width: 360px;
      height: 50px;
      line-height: 50px;
      color: #fff;
      background-color: @blue;
      margin: auto;
      text-align: center;
      cursor: pointer;
    }
    .verify_box {
      width: 360px;
      margin: 0 auto 20px;
      /deep/.slide-box {
        width: 100%;
        position: relative;
        box-sizing: border-box;
        canvas {
          position: absolute;
          left: 0;
          top: -140px;
          display: none;
          width: 100%;
          box-sizing: border-box;
        }
        .slide-verify-block {
          width: 70px;
          height: 135px;
        }
        &:hover {
          canvas {
            display: block;
          }
        }
      }
    }
  }
}
</style>